package com.anuo.app.modules.study.studyjedis;


import com.anuo.app.common.utils.JsonUtil;
import com.anuo.app.modules.study.entity.Product;
import com.fasterxml.jackson.core.type.TypeReference;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

import java.util.HashMap;
import java.util.Map;

/**
 * 研究状态: 常用已完成
 * 待封装成易容的api 参考 jeesite
 * http://www.baeldung.com/jedis-java-redis-client-library
 */
public class StudyJedis {

    public static void main(String[] args) {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        String redisIp = "192.168.2.113";//ha 集群ip
        int port = 6378;
        JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisIp, port, Protocol.DEFAULT_TIMEOUT, null);
        try (Jedis jedis = jedisPool.getResource()) {

            Product product = new Product();
            String productJson= JsonUtil.toJson(product);
            //string
            jedis.set("cpu", productJson);
            String productJsonRedis=jedis.get("cpu");
            Product productNew=JsonUtil
                    .fromJson(productJsonRedis, new  TypeReference<Product>(){} );
        }
    }

    public void StudyJedis(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        //默认是8个连接, 一个连接约1000的qps , 如果并发比较大需要上调此值,
        //  参考: https://yq.aliyun.com/articles/236383?spm=5176.100239.blogcont236384.16.uZMmhS
        jedisPoolConfig.setMaxTotal(20);

        String redisIp = "192.168.2.113";//ha 集群ip
        int port = 6378;

        JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisIp, port, Protocol.DEFAULT_TIMEOUT, null);

        try (Jedis jedis = jedisPool.getResource()) {
            //string
            jedis.set("name", "anuo");
            String name = jedis.get("name");
            //list
            jedis.lpush("msgList", "he");
            jedis.lpush("msgList", "llo");
            jedis.lpush("msgList", "world");
            //hash
            jedis.hset("rowHash", "id", "skds");
            jedis.hset("rowHash", "name", "jk");
            jedis.hset("rowHash", "sex", "1");
            jedis.hset("rowHash", "address", "成都");

            //set (无序不重复list)
            jedis.sadd("msgSet", "I");
            jedis.sadd("msgSet", "am");
            jedis.sadd("msgSet", "set");
            //sorted set (有序不重复list)
            final Map<String, Integer> scores = new HashMap<>();
            scores.put("playerOne", 2);
            scores.put("playerTwo", 5);
            scores.put("playerThree", 1);

            scores.keySet().forEach(player -> {
                jedis.zadd("ranking", scores.get(player), player);
            });

            String player = jedis.zrevrange("ranking", 0, 1).iterator().next();
            long rank = jedis.zrevrank("ranking", "PlayerOne");

            //pipeline
        }

    }


}
